<template>
  <div>
    <!--非枚举-->
    <div class="L-input-row" v-if="uitype !== 'enum'">
      <van-row type="flex" align="center" >
        <van-col :span="23">
          <input
            :readonly="!['string', 'double', 'code', 'money', 'int'].includes(uitype) || dateTypeArr.indexOf(formItem.viewcondition_filtertype) > -1"
            :type="inputType"
            v-model="itemValue"
            @click="handleClick"
            :placeholder="formItem.viewcondition_comparison === 'notempty' ? '非空' : '请输入' + formItem.viewcondition_title"
            :disabled="formItem.viewcondition_comparison === 'notempty'"
          />
        </van-col>
        <van-col :span="1" class="L-text-align-center">
          <i class="iconfont icon-xiayibu2" v-if="inputTypeArr.indexOf(uitype) === -1"></i>
        </van-col>
      </van-row>
    </div>

    <!-- 枚举 -->
    <div v-else>
      <div class="L-margin-top-20">
        <span
          v-for="(item, index) in formItem.viewcondition_enum_property"
          :key="index"
          class="L-checked-btn"
          :class="itemValue.includes(item.id) ? 'L-checked-btn-on' : ''"
          @click="() => handleClick(item)"
          >{{ item.enumProperty.sname }}</span
        >
      </div>
    </div>
    <!-- 日历插件 -->
    <van-popup v-model:show="showCalendar" position="bottom">
      <van-date-picker v-model="currentDate" :columns-type="dateType" @confirm="handleConfirm" :min-date="minDate" :max-date="maxDate" />
    </van-popup>
    <!-- <van-calendar v-model:show="showCalendar" :type="formItem.viewcondition_uitypeExp === 'normal' ? 'single' : 'range'"
      :min-date="minDate" :max-date="maxDate" @confirm="handleConfirm" /> -->
    <!-- 数字键盘 -->
    <van-number-keyboard :show="showNumberKeyboard" extra-key="." @blur="showNumberKeyboard = false" @input="handleClickNumberKeyBoard" @delete="handleClickNumberKeyBoardDelete" />

    <!-- 参照弹窗 -->
    <van-popup v-model:show="showeRefPopup" position="right" style="width: 100%; height: 100%">
      <div v-if="showeRefPopup">
        <OrgRef
          :refParams="refParams"
          :refObject="formItem.viewcondition_joinobject"
          :handleRefClick="handleRefClick"
          :handleRefCancle="handleRefCancle"
          refMode="normal"
          v-if="formItem.viewcondition_joinobject === 'dep' || formItem.viewcondition_joinobject === 'employee'"
        >
        </OrgRef>
        <Ref :refParams="refParams" :refObject="formItem.viewcondition_joinobject" :handleRefClick="handleRefClick" :handleRefCancle="handleRefCancle" refMode="normal" v-else></Ref>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import Ref from '../Ref/Ref.vue'
import OrgRef from '../Ref/OrgRef.vue'
import emitter from '@/utils/emitter'

import { ref, onActivated, watch, provide, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
import { useRefStore } from '@/stores/ref'
const refStore = useRefStore()

const inputTypeArr = ['double', 'money', 'int', 'string', 'code', 'ref']

const dateTypeArr = ['datetime', 'yearmonth']
const numberTypeArr = ['double', 'money', 'int']
const booleanTypeArr = ['bool', 'boolean']
const stringTypeArr = ['code', 'string']

const props = defineProps({
  uitype: String,
  formItem: {
    type: Object,
    default: null
  }
})

const emits = defineEmits(['handleUpdate'])

const inputType = ref('text')

if (numberTypeArr.indexOf(props.uitype) !== -1) {
  inputType.value = 'number'
}

const itemValue = ref('')
const itemValueId = ref('')

const showeRefPopup = ref(false)
const refParams = ref({
  object: props.formItem.viewcondition_joinobject,
  toobject: props.formItem.viewcondition_object,
  field: props.formItem.viewcondition_field ||props.formItem.sField,
  // sRefKey: props.formItem.viewcondition_id,
  classname: props.formItem.classname,
  viewId: props.formItem.viewcondition_refmobile,
  inview: 'sname:in;'
})

// const refParams = ref({
//   object: props.formItem.idJoinObject,
//   toobject: props.formItem.idObject,
//   field: props.formItem.sField,
//   sRefKey: props.formItem.sRefKey,
//   classname: props.formItem.classname,
//   params: "",
//   inview: ""
// });

watch(itemValue, (val) => {
  emits('handleUpdate', props.formItem, itemValue.value, itemValueId.value)
})
watch(
  () => props.formItem,
  (val) => {
    refParams.value.object = props.formItem.viewcondition_joinobject
    refParams.value.toobject = props.formItem.viewcondition_object
    refParams.value.field = props.formItem.viewcondition_field
    refParams.value.id = props.formItem.viewcondition_refmobile
  }
)

function handleRefClick(item) {
  itemValue.value = item.title
  itemValueId.value = item.id
  //  itemId.value = item.id;

  showeRefPopup.value = false
}

function handleRefCancle() {
  showeRefPopup.value = false
}

function handleClick(item) {
  const { formItem, tableType, jsondata, bodyDataName, bodyDataIndex } = props
  // 参照
  if (props.uitype === 'ref') {
    showeRefPopup.value = true
    return
  }
  //时间
  if (dateTypeArr.indexOf(props.uitype) !== -1 || dateTypeArr.indexOf(props.formItem.viewcondition_filtertype) > -1) {
    if (dateTypeArr.indexOf(props.uitype) !== -1) {
      if (props.uitype == 'datetime') {
        currentDate.value = currentDateOption
        dateType.value = ['year', 'month', 'day']
      } else {
        dateType.value = ['year', 'month']
        currentDate.value = currentDateOption.slice(0, 2)
      }
    } else if (props.uitype == 'string' && props.formItem.viewcondition_filtertype == 'yearmonth') {
      dateType.value = ['year', 'month']
      currentDate.value = currentDateOption.slice(0, 2)
    }
    showCalendar.value = true
  }

  if (numberTypeArr.indexOf(props.uitype) !== -1) {
    // showNumberKeyboard.value = true;
  }

  //枚举
  if (props.uitype === 'enum') {
        console.log(itemValue)

    if (itemValue.value.includes(item.id)) {
      // itemValue.value = itemValue.value.split(';').filter(i => {
      //   return i !== item.enumProperty.sname
      // }).join(';')
      itemValue.value = itemValue.value.split(';').filter(i => {
        return i !== item.id
      }).join(';')
      itemValueId.value = itemValueId.value.split(';').filter(i => {
        return i !== item.id
      }).join(';')
    } else {
      itemValue.value = itemValue.value ? itemValue.value + ';' + item.id : item.id
      itemValueId.value = itemValueId.value ?  itemValueId.value + ';' + item.id : item.id
    }

    // itemValue.value = e.target.innerText;
  }
}

const showCalendar = ref(false)
const minDate = new Date(2012, 0, 1)
const maxDate = new Date(2030, 0, 31)
const currentDate = ref([])
const currentDateOption = [
  new Date().getFullYear(), // 当前年
  new Date().getMonth() + 1, // 当前月（注意月份从0开始）
  new Date().getDate() // 当前日
]
const dateType = ref([])

const formatDate = (date) => `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`

const formatDate1 = (date) => {
  let monthStr = ''
  if (date.getMonth() + 1 < 10) {
    monthStr = `0${date.getMonth() + 1}`
  } else {
    monthStr = `${date.getMonth() + 1}`
  }
  return `${date.getFullYear()}-${monthStr}-${date.getDate()}`
}
// 格式化日期为 YYYY-MM-DD
const formatSelectedDate = (v) => {
  const [year, month, day] = v
  let date
  if (day) {
   date = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`

  } else {
   date = `${year}-${month.toString().padStart(2, '0')}`
  }
  return date
}
function handleConfirm({ selectedValues }) {
  currentDate.value = selectedValues
  itemValue.value = formatSelectedDate(selectedValues)
  showCalendar.value = false
  // const { viewcondition_uitypeExp } = props.formItem;

  // if (viewcondition_uitypeExp === "normal") {
  //   showCalendar.value = false;
  //   itemValue.value = formatDate1(values);
  // } else {
  //   const [start, end] = values;
  //   showCalendar.value = false;
  //   itemValue.value = `${formatDate(start)} - ${formatDate(end)}`;
  // }
}

const showNumberKeyboard = ref(false)
function handleClickNumberKeyBoard(value) {
  itemValue.value = `${itemValue.value}${value}`
}
function handleClickNumberKeyBoardDelete() {
  itemValue.value = itemValue.value.slice(0, -1)
}

function handleClear() {
  itemValue.value = ''
}

onMounted(() => {
  emitter.on('clearFilterInputData', () => {
    handleClear()
  })
})
</script>

<style scoped>
.L-input-row {
  background: #f6f6f6;
  padding: 5px 10px;
  border-radius: 6px;
}

.L-input-row input {
  background: none;
  border: none;
  outline: none;
  padding: 0;
  margin: 0;
  font-size: 14px;
  /* 根据需要调整字体大小 */
  color: currentColor;
  /* 使用当前文本颜色 */
  width: 100%;
}
</style>
